<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="宿舍" prop="roomId">
            <!-- <el-input v-model="queryParams.roomId" placeholder="请输入宿舍ID" clearable style="width: 240px" @keyup.enter="handleQuery" /> -->
            <DormitoryTree ref="dormitoryTree" @node-click="handleNodeClick" />
          </el-form-item>
          <el-form-item label="学生姓名" prop="studentName">
            <el-input v-model="queryParams.studentName" placeholder="请输入学生姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="所在班级" prop="classId">
            <class-tree v-model="queryParams.classId" gradeDisabled />
            <!-- <el-input v-model="queryParams.classId" placeholder="请输入班级ID" clearable style="width: 240px" @keyup.enter="handleQuery" /> -->
            <!-- <el-autocomplete
              v-model="queryParams.className"
              :fetch-suggestions="searchClassInfo"
              :trigger-on-focus="false"
              placeholder="请选择班级"
              clearable
              @select="((e) => { queryParams.classId = e.id;  queryParams.className = e.className; })"
            >
              <template #default="{ item }">
                <div class="value">{{ item.className }}</div>
              </template>
            </el-autocomplete> -->
          </el-form-item>
          <el-form-item label="学号" prop="studentNo">
            <el-input v-model="queryParams.studentNo" placeholder="请输入学号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="时间" style="width: 308px">
            <el-date-picker
              v-model="dateRangeAttendanceDate"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <!-- <el-form-item label="创建时间" style="width: 308px">
            <el-date-picker
              v-model="dateRangeCreateTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item> -->
          <el-form-item>
            <el-button-group>
              <el-button @click="timeClick(1)">当天</el-button>
              <el-button @click="timeClick(2)">本周</el-button>
              <el-button @click="timeClick(3)">本月</el-button>
            </el-button-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['dormitory:attendanceDetail:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['dormitory:attendanceDetail:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['dormitory:attendanceDetail:remove']"
              >删除</el-button
            >
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['dormitory:attendanceDetail:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        height="calc(100vh - 420px)"
        stripe
        v-loading="loading"
        :data="attendanceDetailList"
        @selection-change="handleSelectionChange"
        @row-dblclick="(row)=>handleDetail(row)"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <!-- <el-table-column label="ID" align="center" prop="id" v-if="true" /> -->
        <el-table-column label="姓名" align="center" prop="studentName" />
        <el-table-column label="班级" align="center" width="120" prop="className" />
        <el-table-column label="学号" align="center" width="120" prop="studentNo" />
        <el-table-column label="宿舍楼" align="center" width="120" prop="buildingName" />
        <el-table-column label="宿舍楼层" align="center" prop="floorName" />
        <el-table-column label="宿舍号" align="center" prop="roomName" />
        <el-table-column label="日期" align="center" prop="attendanceDate" width="100">
          <template #default="scope">
            <span>{{ parseTime(scope.row.attendanceDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="早上出寝" align="center">
          <el-table-column label="打卡时间" align="center" width="100" prop="validatndTime1" />
          <el-table-column label="打卡结果" align="center" width="100" prop="validatndResult1">
            <template #default="scope">
              <dict-tag :options="sg_validatnd_result" :value="scope.row.validatndResult1" />
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="中午入寝" align="center">
          <el-table-column label="打卡时间" align="center" width="100" prop="validatndTime2" />
          <el-table-column label="打卡结果" align="center" width="100" prop="validatndResult2">
            <template #default="scope">
              <dict-tag :options="sg_validatnd_result" :value="scope.row.validatndResult2" />
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="中午出寝" align="center">
          <el-table-column label="打卡时间" align="center" width="100" prop="validatndTime3" />
          <el-table-column label="打卡结果" align="center" width="100" prop="validatndResult3">
            <template #default="scope">
              <dict-tag :options="sg_validatnd_result" :value="scope.row.validatndResult3" />
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="下午入寝" align="center">
          <el-table-column label="打卡时间" align="center" width="100" prop="validatndTime4" />
          <el-table-column label="打卡结果" align="center" width="100" prop="validatndResult4">
            <template #default="scope">
              <dict-tag :options="sg_validatnd_result" :value="scope.row.validatndResult4" />
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="下午出寝" align="center">
          <el-table-column label="打卡时间" align="center" width="100" prop="validatndTime5" />
          <el-table-column label="打卡结果" align="center" width="100" prop="validatndResult5">
            <template #default="scope">
              <dict-tag :options="sg_validatnd_result" :value="scope.row.validatndResult5" />
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="晚上入寝" align="center">
          <el-table-column label="打卡时间" align="center" width="100" prop="validatndTime6" />
          <el-table-column label="打卡结果" align="center" width="100" prop="validatndResult6">
            <template #default="scope">
              <dict-tag :options="sg_validatnd_result" :value="scope.row.validatndResult6" />
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="关联的请假审批单" align="center" prop="roomId" width="400">
          <template #default="scope">
            <div class="leave-list">
              <p v-for="(item,index) in scope.row.leaveList" :key="index" class="leave-item">
                <!-- 请假时间+请假类型+请假事由 -->
                <span>时间：{{ item.startTime +" ~ "+item.endTime }}</span>
                <span>类型：<dict-tag :options="leave_type" :value="item.leaveType" /></span>
                <span>事由：{{ item.leaveReason}}</span>
              </p>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <!-- <el-tooltip content="修改" placement="top">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['dormitory:attendanceDetail:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['dormitory:attendanceDetail:remove']"
              ></el-button>
            </el-tooltip> -->
            <el-button link type="primary" icon="View" @click="handleDetail(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改宿舍考勤明细对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="740px" append-to-body>
      <el-form ref="attendanceDetailFormRef" :model="form" :rules="rules" label-width="100px" :inline="true" class="add-form" disabled>
        <el-form-item label="学生" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入学生" />
        </el-form-item>
        <el-form-item label="宿舍楼" prop="buildingName">
          <el-input v-model="form.buildingName" placeholder="请输入宿舍楼" />
        </el-form-item>
        <el-form-item label="班级" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级" />
        </el-form-item>
        <el-form-item label="楼层" prop="floorName">
          <el-input v-model="form.floorName" placeholder="请输入宿舍" />
        </el-form-item>
        <el-form-item label="学号" prop="studentNo">
          <el-input v-model="form.studentNo" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="宿舍" prop="roomName">
          <el-input v-model="form.roomName" placeholder="请输入宿舍" />
        </el-form-item>
        <el-form-item label="考勤日期" prop="attendanceDate">
          <el-date-picker clearable v-model="form.attendanceDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择考勤时间">
          </el-date-picker>
        </el-form-item>
        <table border="1" align="center" cellspacing="0" cellpadding="0" class="detail-table">
          <thead>
            <tr>
              <th>早上出寝</th>
              <th>中午入寝</th>
              <th>中午出寝</th>
              <th>下午入寝</th>
              <th>下午出寝</th>
              <th>晚上入寝</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>
                <p>
                  <span>{{ form.validatndTime1 || '' }} </span><dict-tag :options="sg_validatnd_result" :value="form.validatndResult1" />
                </p>
              </td>
              <td>
                <p>
                  <span>{{ form.validatndTime2 || '' }} </span><dict-tag :options="sg_validatnd_result" :value="form.validatndResult2" />
                </p>
              </td>
              <td>
                <p>
                  <span>{{ form.validatndTime3 || '' }}</span> <dict-tag :options="sg_validatnd_result" :value="form.validatndResult3" />
                </p>
              </td>
              <td>
                <p>
                  <span>{{ form.validatndTime4 || '' }} </span><dict-tag :options="sg_validatnd_result" :value="form.validatndResult4" />
                </p>
              </td>
              <td>
                <p>
                  <span>{{ form.validatndTime5 || '' }} </span><dict-tag :options="sg_validatnd_result" :value="form.validatndResult5" />
                </p>
              </td>
              <td>
                <p>
                  <span>{{ form.validatndTime6 || '' }} </span><dict-tag :options="sg_validatnd_result" :value="form.validatndResult6" />
                </p>
              </td>
            </tr>
          </tbody>
        </table>
        <section class="leave-view">
          <b>关联的请假审批单：</b>
          <p v-if="form.leaveList.length === 0">无</p>
          <div class="leave-list">
            <p v-for="(item,index) in form.leaveList" :key="index" class="leave-item">
              <!-- 请假时间+请假类型+请假事由 -->
              <span>时间：{{ item.startTime +" ~ "+item.endTime }}</span>
              <span>类型：<dict-tag :options="leave_type" :value="item.leaveType" /></span>
              <span>事由：{{ item.leaveReason}}</span>
            </p>
          </div>
        </section>
        <!-- <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item> -->
      </el-form>
      <!-- <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template> -->
    </el-dialog>
  </div>
</template>

<script setup name="AttendanceDetail" lang="ts">
import {
  listAttendanceDetail,
  getAttendanceDetail,
  delAttendanceDetail,
  addAttendanceDetail,
  updateAttendanceDetail
} from '@/api/dormitory/attendanceDetail';
import { AttendanceDetailVO, AttendanceDetailQuery, AttendanceDetailForm } from '@/api/dormitory/attendanceDetail/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sg_validatnd_result, leave_type } = toRefs<any>(proxy?.useDict('sg_validatnd_result', 'leave_type'));

const attendanceDetailList = ref<AttendanceDetailVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangeAttendanceDate = ref<[DateModelType, DateModelType]>(['', '']);
const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const attendanceDetailFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: AttendanceDetailForm = {
  id: undefined,
  studentId: undefined,
  classId: undefined,
  roomId: undefined,
  attendanceDate: undefined,
  remark: undefined
};
const data = reactive<PageData<AttendanceDetailForm, AttendanceDetailQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentId: undefined,
    classId: undefined,
    roomId: undefined,
    params: {
      attendanceDate: undefined,
      createTime: undefined
    }
  },
  rules: {
    id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
    studentId: [{ required: true, message: '学生ID不能为空', trigger: 'blur' }],
    classId: [{ required: true, message: '班级ID不能为空', trigger: 'blur' }],
    roomId: [{ required: true, message: '宿舍ID不能为空', trigger: 'blur' }],
    attendanceDate: [{ required: true, message: '考勤时间不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询宿舍考勤明细列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeAttendanceDate.value, 'AttendanceDate');
  proxy?.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime');
  const res = await listAttendanceDetail(queryParams.value);
  for (let row of res.rows) {
    for (let item of row.details) {
      row[`validatndResult${item.attendanceShift}`] = item.validatndResult;
      row[`validatndTime${item.attendanceShift}`] = proxy?.parseTime(item.validatndTime, '{h}:{i}:{s}');
    }
  }
  attendanceDetailList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  dormitoryTree.value.clear();
  form.value = { ...initFormData };
  attendanceDetailFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeAttendanceDate.value = ['', ''];
  dateRangeCreateTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.buildingId = undefined;
  queryParams.value.floorId = undefined;
  queryParams.value.roomId = undefined;
  queryParams.value.className = undefined;
  dormitoryTree.value.clear();
  handleQuery();
};

import { listClassInfo } from '@/api/office/class';

const searchClassInfo = (queryString, cb) => {
  listClassInfo({ className: queryString }).then((response) => {
    cb(response.rows);
  });
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: AttendanceDetailVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加宿舍考勤明细';
};

/** 修改按钮操作 */
const handleDetail = async (row?: AttendanceDetailVO) => {
  reset();
  // const _id = row?.id || ids.value[0];
  // const res = await getAttendanceDetail(_id);
  // Object.assign(form.value, res.data);
  Object.assign(form.value, row);
  dialog.visible = true;
  dialog.title = '详情';
};

/** 提交按钮 */
const submitForm = () => {
  attendanceDetailFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAttendanceDetail(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addAttendanceDetail(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: AttendanceDetailVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除宿舍考勤明细编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delAttendanceDetail(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'dormitory/attendanceDetail/export',
    {
      ...queryParams.value
    },
    `宿舍考勤明细_${new Date().getTime()}.xlsx`
  );
};

const dormitoryTree = ref();
/** 节点单击事件 */
const handleNodeClick = (data: any) => {
  queryParams.value.buildingId = undefined;
  queryParams.value.floorId = undefined;
  queryParams.value.roomId = undefined;
  switch (data.type) {
    case 'T':
      break;
    case 'B':
      queryParams.value.buildingId = data.sourceId;
      break;
    case 'F':
      queryParams.value.floorId = data.sourceId;
      break;
    case 'R':
      queryParams.value.roomId = data.sourceId;
      break;
  }
};

const timeClick = async (type: number) => {
  let startTime = new Date();
  let endTime = new Date();
  if (type == 2) {
    const days = [0, 1, 2, 3, 4, 5, 6];
    const dayOfWeek = days[startTime.getDay()];
    startTime.setDate(startTime.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1));
  } else if (type == 3) {
    startTime.setDate(1);
  }
  dateRangeAttendanceDate.value = [proxy?.parseTime(startTime, '{y}-{m}-{d}') + ' 00:00:00', proxy?.parseTime(endTime, '{y}-{m}-{d}') + ' 23:59:59'];
};

onMounted(() => {
  timeClick(1);
  getList();
});
</script>

<style lang="scss" scoped>
.leave-list {
  //cursor: pointer;
}
.leave-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  span {
    display: inline-block;
    display: flex;
    color: #2d8cf0;
  }
}
.detail-table {
  width: 95%;
  border-color: #fff;
  th {
    height: 40px;
  }
  tbody {
    tr {
      td {
        p {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          span {
            display: inline-block;
            height: 30px;
            line-height: 30px;
          }
        }
      }
    }
  }
}
.leave-view {
  width: 95%;
  padding-left: 20px;
  b {
    display: inline-block;
    font-size: 15px;
    padding-top: 20px;
  }
}
</style>
